<template>
  <Layer :layer="layer" @confirm="submit">
    <el-form :model="ruleForm" :rules="rules" ref="form" label-width="120px" style="margin-right: 30px">
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="ruleForm.name" placeholder="请输入角色名称"></el-input>
      </el-form-item>
      <el-form-item label="角色标识" prop="roleId">
        <el-input v-model="ruleForm.roleId" placeholder="请输入角色标识"></el-input>
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="ruleForm.description" placeholder="请输入角色描述"></el-input>
      </el-form-item>
    </el-form>
  </Layer>
</template>

<script lang="ts" setup>
import {ref, toRefs, reactive, onMounted} from "vue";
import Layer from "@/components/layer/index.vue";
import {add, update} from "@/api/system/role";
import {ElMessage} from "element-plus";

const props = defineProps({
  layer: {
    type: Object,
    default() {
      return {
        show: false,
        title: "",
        showButton: true,
      };
    },
  },
});
const {layer} = toRefs(props);
const emits = defineEmits(["getTableData"]);
const form = ref();

let ruleForm = ref({
  name: "",
  roleId: "",
  description: "",
})

const rules = {
  name: [{required: true, message: "请输入角色名称", trigger: "blur"}],
  role: [{required: true, message: "请输入角色标识", trigger: "blur"}],
};

init()

function init() { // 用于判断新增还是编辑功能
  if (props.layer.row) {
    ruleForm.value = JSON.parse(JSON.stringify(props.layer.row)) // 数量量少的直接使用这个转
  } else {

  }
}

const submit = () => {
  form.value.validate((valid: boolean) => {
    if (valid) {
      let params = ruleForm.value;
      if (props.layer.row) {
        updateForm(params);
      } else {
        addForm(params);
      }
    } else {
      return false;
    }
  });
};
// 新增提交事件
const addForm = (params: object) => {
  add(params).then((res) => {
    ElMessage({
      type: "success",
      message: "新增成功",
    });
    layer.value.show = false
    emits("getTableData", true);
  });
};

// 编辑提交事件
const updateForm = (params: object) => {
  update(params).then((res) => {
    ElMessage({
      type: "success",
      message: "编辑成功",
    });
    emits("getTableData", false);
  });
};
</script>

<style lang="scss" scoped>
</style>